document.addEventListener('DOMContentLoaded', function () {
    let musicPlaying = false;
    let currentOpenStory = null;
    let storyData = null;

    function renderStory() {
        const monthsContainer = document.getElementById('months-container');
        monthsContainer.innerHTML = '';
        // 如果没有祝福
        if (!storyData || !storyData.story || !storyData.story.length === 0) {
            return;
        }

        // 按ID倒序排序（最新的在前面）
        storyData.story.sort((a, b) => a.id - b.id);
        // 创建祝福卡片
        storyData.story.forEach(item => {
            // 动态渲染气球
            const balloon = `
                    <div class="month-balloon ${item.special ? 'special' : ''}" data-month="${item.month}">
                      <div class="balloon">
                        <div class="balloon-body" style="background: linear-gradient(45deg, ${item.gradient.join(',')});">
                          <span class="month-text">${item.monthText}</span>
                          ${item.special ? '<div class="birthday-crown">👑</div>' : ''}
                        </div>
                        <div class="balloon-string"></div>
                      </div>
                      <div class="month-story hidden">
                        <h3>${item.title}</h3>
                        <p>${item.story}</p>
                        <div class="story-image">
                          <img src="${item.img}" alt="${item.monthText}照片">
                        </div>
                        ${item.wishes ? `<div class="birthday-wishes"><p>${item.wishes}</p></div>` : ''}
                      </div>
                    </div>
                  `;
            monthsContainer.insertAdjacentHTML('beforeend', balloon);
        });
    }

    function loadMemoriesData() {
        fetch('../data/story.json')
            .then(response => response.json())
            .then(data => {
                storyData = data || [];
                renderStory();
                // 添加事件监听器
                addEventListeners();
            });

    }

    loadMemoriesData();


    // 音频元素
    const backgroundMusic = document.getElementById('background-music');
    const balloonPop = document.getElementById('balloon-pop');
    const musicToggle = document.getElementById('music-toggle');

    // 初始化
    init();

    function init() {
        // 启动粒子系统
        if (typeof initParticles === 'function') {
            initParticles();
        }


        // 尝试自动播放音乐
        tryAutoPlayMusic();

        // 添加滚动动画
        addScrollAnimations();

        // 添加特殊效果
        addSpecialEffects();
    }

    function tryAutoPlayMusic() {
        const playPromise = backgroundMusic.play();
        if (playPromise !== undefined) {
            playPromise.then(() => {
                musicPlaying = true;
                musicToggle.textContent = '🎵';
                musicToggle.style.animation = 'musicPulse 2s infinite';
            }).catch(() => {
                musicPlaying = false;
                musicToggle.textContent = '🔇';
                // 添加用户交互启动音乐
                document.addEventListener('click', () => {
                    if (!musicPlaying) {
                        backgroundMusic.play().then(() => {
                            musicPlaying = true;
                            musicToggle.textContent = '🎵';
                            musicToggle.style.animation = 'musicPulse 2s infinite';
                        });
                    }
                }, {once: true});
            });
        }
    }

    function addEventListeners() {
        // 音乐控制
        musicToggle.addEventListener('click', toggleMusic);

        // 气球点击事件
        document.querySelectorAll('.month-balloon').forEach(balloon => {
            balloon.addEventListener('click', handleBalloonClick);
        });

        // 键盘事件
        document.addEventListener('keydown', handleKeyPress);

        // 触摸事件
        addTouchEvents();
    }

    function toggleMusic() {

        if (musicPlaying) {
            backgroundMusic.pause();
            musicToggle.textContent = '🔇';
            musicToggle.style.animation = 'none';
            musicPlaying = false;
        } else {
            backgroundMusic.play().then(() => {
                musicToggle.textContent = '🎵';
                musicToggle.style.animation = 'musicPulse 2s infinite';
                musicPlaying = true;
            }).catch(e => {
                console.log('音乐播放失败:', e);
            });
        }
    }

    function handleBalloonClick(e) {
        const balloon = e.currentTarget;
        const month = balloon.dataset.month;
        const story = balloon.querySelector('.month-story');

        // 播放气球音效
        if (balloonPop) {
            balloonPop.currentTime = 0;
            balloonPop.play().catch(e => console.log('音效播放失败:', e));
        }

        // 添加点击动画
        balloon.classList.add('clicked');
        setTimeout(() => {
            balloon.classList.remove('clicked');
        }, 500);

        // 如果当前故事已经打开，则关闭它
        if (currentOpenStory === story && !story.classList.contains('hidden')) {
            closeStory(story);
            currentOpenStory = null;
            return;
        }

        // 关闭之前打开的故事
        if (currentOpenStory && !currentOpenStory.classList.contains('hidden')) {
            closeStory(currentOpenStory);
        }

        // 打开新故事
        openStory(story);
        currentOpenStory = story;

        // 特殊月份的特殊效果
        if (month === '12') {
            createBirthdayEffect();
        } else if (month === '0') {
            createBirthEffect();
        }

        // 滚动到故事位置
        setTimeout(() => {
            story.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });
        }, 300);
    }

    function openStory(story) {
        story.classList.remove('hidden');
        story.classList.add('expanding');

        setTimeout(() => {
            story.classList.add('show');
        }, 50);

        // 图片飞入动画
        const img = story.querySelector('.story-image img');
        if (img) {
            img.style.transform = 'translateX(-100px) rotate(-10deg) scale(0.8)';
            img.style.opacity = '0';

            setTimeout(() => {
                img.style.transition = 'all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
                img.style.transform = 'translateX(0) rotate(0deg) scale(1)';
                img.style.opacity = '1';
            }, 200);
        }

        // 文字打字机效果
        const text = story.querySelector('p');
        if (text) {
            const originalText = text.textContent;
            text.textContent = '';

            setTimeout(() => {
                typeWriter(text, originalText, 30);
            }, 400);
        }
    }

    function closeStory(story) {
        story.classList.remove('show', 'expanding');

        setTimeout(() => {
            story.classList.add('hidden');
        }, 300);
    }

    function typeWriter(element, text, speed) {
        let i = 0;

        function type() {
            if (i < text.length) {
                element.textContent += text.charAt(i);
                i++;
                setTimeout(type, speed);
            }
        }

        type();
    }

    function createBirthdayEffect() {
        // 生日特效：彩带和烟花
        if (typeof createConfetti === 'function') {
            createConfetti();
        }

        setTimeout(() => {
            if (typeof createFireworks === 'function') {
                createFireworks();
            }
        }, 500);

        // 创建生日祝福文字
        createFloatingText('生日快乐！', window.innerWidth / 2, window.innerHeight / 2);
    }

    function createBirthEffect() {
        // 出生特效：温柔的粒子效果
        createGentleParticles();
        createFloatingText('小天使降临', window.innerWidth / 2, window.innerHeight / 2);
    }

    function createFloatingText(text, x, y) {
        const textElement = document.createElement('div');
        textElement.textContent = text;
        textElement.style.cssText = `
            position: fixed;
            left: ${x}px;
            top: ${y}px;
            font-family: 'Fredoka One', cursive;
            font-size: 36px;
            color: #ff6b9d;
            text-shadow: 0 0 20px rgba(255, 107, 157, 0.8);
            pointer-events: none;
            z-index: 1000;
            transform: translate(-50%, -50%) scale(0);
        `;

        document.body.appendChild(textElement);

        textElement.animate([
            {
                transform: 'translate(-50%, -50%) scale(0) rotate(-10deg)',
                opacity: 0
            },
            {
                transform: 'translate(-50%, -50%) scale(1.2) rotate(0deg)',
                opacity: 1
            },
            {
                transform: 'translate(-50%, -50%) scale(1) rotate(0deg)',
                opacity: 1
            },
            {
                transform: 'translate(-50%, -50%) scale(0) rotate(10deg)',
                opacity: 0
            }
        ], {
            duration: 3000,
            easing: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)'
        }).onfinish = () => {
            textElement.remove();
        };
    }

    function createGentleParticles() {
        const colors = ['rgba(255, 182, 193, 0.8)', 'rgba(255, 240, 245, 0.8)', 'rgba(255, 228, 225, 0.8)'];

        for (let i = 0; i < 30; i++) {
            const particle = document.createElement('div');
            particle.style.cssText = `
                position: fixed;
                width: 8px;
                height: 8px;
                background: ${colors[Math.floor(Math.random() * colors.length)]};
                border-radius: 50%;
                pointer-events: none;
                z-index: 1000;
                left: ${Math.random() * window.innerWidth}px;
                top: ${Math.random() * window.innerHeight}px;
            `;

            document.body.appendChild(particle);

            particle.animate([
                {
                    transform: 'scale(0) translateY(0)',
                    opacity: 0
                },
                {
                    transform: 'scale(1) translateY(-20px)',
                    opacity: 1
                },
                {
                    transform: 'scale(0) translateY(-40px)',
                    opacity: 0
                }
            ], {
                duration: 2000 + Math.random() * 1000,
                easing: 'ease-out'
            }).onfinish = () => {
                particle.remove();
            };
        }
    }

    function handleKeyPress(e) {
        switch (e.key) {
            case ' ':
                e.preventDefault();
                toggleMusic();
                break;
            case 'Escape':
                if (currentOpenStory) {
                    closeStory(currentOpenStory);
                    currentOpenStory = null;
                }
                break;
            case 'ArrowLeft':
                navigateToPrevious();
                break;
            case 'ArrowRight':
                navigateToNext();
                break;
        }
    }

    function navigateToPrevious() {
        window.location.href = 'welcome.html';
    }

    function navigateToNext() {
        window.location.href = 'memories.html';
    }

    function addTouchEvents() {
        let touchStartX = 0;
        let touchStartY = 0;

        document.addEventListener('touchstart', (e) => {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
        });

        document.addEventListener('touchend', (e) => {
            const touchEndX = e.changedTouches[0].clientX;
            const touchEndY = e.changedTouches[0].clientY;

            const deltaX = touchEndX - touchStartX;
            const deltaY = touchEndY - touchStartY;

            // 水平滑动
            if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
                if (deltaX > 0) {
                    // 向右滑动 - 上一页
                    navigateToPrevious();
                } else {
                    // 向左滑动 - 下一页
                    navigateToNext();
                }
            }
        });
    }

    function addScrollAnimations() {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.animation = 'slideInUp 0.8s ease-out';
                }
            });
        }, {
            threshold: 0.1
        });

        document.querySelectorAll('.month-balloon').forEach(balloon => {
            observer.observe(balloon);
        });
    }

    function addSpecialEffects() {
        // 鼠标跟随效果
        let mouseTrail = [];

        document.addEventListener('mousemove', (e) => {
            // 创建跟随粒子
            if (Math.random() < 0.1) {
                const particle = document.createElement('div');
                particle.style.cssText = `
                    position: fixed;
                    width: 4px;
                    height: 4px;
                    background: rgba(255, 107, 157, 0.6);
                    border-radius: 50%;
                    pointer-events: none;
                    z-index: 999;
                    left: ${e.clientX}px;
                    top: ${e.clientY}px;
                `;

                document.body.appendChild(particle);

                particle.animate([
                    {opacity: 1, transform: 'scale(1)'},
                    {opacity: 0, transform: 'scale(0)'}
                ], {
                    duration: 1000,
                    easing: 'ease-out'
                }).onfinish = () => {
                    particle.remove();
                };
            }
        });

        // 定期创建随机粒子
        setInterval(() => {
            if (Math.random() < 0.3) {
                createRandomParticle();
            }
        }, 2000);
    }

    function createRandomParticle() {
        const particle = document.createElement('div');
        const size = Math.random() * 6 + 2;
        const colors = ['#ff6b9d', '#4ecdc4', '#ffe66d', '#ff8a80'];
        const color = colors[Math.floor(Math.random() * colors.length)];

        particle.style.cssText = `
            position: fixed;
            width: ${size}px;
            height: ${size}px;
            background: ${color};
            border-radius: 50%;
            pointer-events: none;
            z-index: 1;
            left: ${Math.random() * window.innerWidth}px;
            top: ${window.innerHeight + 10}px;
        `;

        document.body.appendChild(particle);

        particle.animate([
            {
                transform: 'translateY(0) rotate(0deg)',
                opacity: 0.8
            },
            {
                transform: `translateY(-${window.innerHeight + 100}px) rotate(360deg)`,
                opacity: 0
            }
        ], {
            duration: 3000 + Math.random() * 2000,
            easing: 'ease-out'
        }).onfinish = () => {
            particle.remove();
        };
    }

    // 页面可见性变化处理
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            if (musicPlaying) {
                backgroundMusic.pause();
            }
        } else {
            if (musicPlaying) {
                backgroundMusic.play().catch(e => console.log('恢复播放失败:', e));
            }
        }
    });

    console.log('成长故事页面已加载完成！');
    console.log('操作提示：');
    console.log('- 点击气球查看成长故事');
    console.log('- 空格键控制音乐');
    console.log('- ESC键关闭当前故事');
    console.log('- 左右箭头键或滑动切换页面');
});

